package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.woniu.constant.OrderConstant;
import com.woniu.dto.OrderDto;
import com.woniu.dto.OrderPayDto;
import com.woniu.mapper.OrderItemMapper;
import com.woniu.pojo.Order;
import com.woniu.mapper.OrderMapper;
import com.woniu.pojo.OrderItem;
import com.woniu.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yellow Docker
 * @since 2022-11-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    public List<Order> getByUserId(Integer userId) {
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = Wrappers.lambdaQuery(Order.class);
        orderLambdaQueryWrapper.eq(Order::getUserId,userId);
        List<Order> orderList = this.list(orderLambdaQueryWrapper);
        return orderList;
    }

    @Override
    public Integer getShopId(Integer id) {
        return orderMapper.getShopId(id);
    }

    @Override
    public String createOrder(OrderDto orderDto) {

        Order order = new Order();
        order.setOrderSn(UUID.randomUUID().toString());
        order.setCreateTime(new Date());
        order.setOrderType(0);
        order.setUserId(orderDto.getUserId());
        order.setStatus(OrderConstant.ORDER_STATUS_UNPAY);
        order.setTotalAmount(orderDto.getPrice());

        this.save(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setId(order.getId());
        orderItem.setOrderSn(order.getOrderSn());
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(orderDto.getProductId());
        orderItem.setProductName(orderDto.getProductName());
        orderItem.setProductPrice(orderDto.getPrice());
        orderItem.setProductQuantity(1);
        orderItem.setShopId(orderDto.getShopId());
        orderItemMapper.insert(orderItem);

        return order.getOrderSn();
    }

    @Override
    public int updateOrderStatus(OrderPayDto orderPayDto) {
        String orderSn = orderPayDto.getOrderSn();
        return orderMapper.updateOrderStatus(orderSn);
    }

    @Override
    public int updateStatus(String orderSn) {
        return orderMapper.updateStatus(orderSn);
    }

    @Override
    public int updateStatusPro(String orderSn) {
        return orderMapper.updateStatusPro(orderSn);
    }
}
